<template>
	<el-container class="main-container full-height">
		<el-header class="main-header">
			<div class="float-left main-title">
				<img src="../../../assets/logo.png" />
				<span class="design-bold">PandaX FlowEngine</span>
				<div style="margin-left: 10px; display: flex">
					<el-tooltip effect="dark" content="展示或关闭拖拽栏">
						<el-button @click="state.showAside = !state.showAside" type="primary" icon="Menu" />
					</el-tooltip>
					<el-tooltip effect="dark" content="展示或关闭设置栏">
						<el-button @click="state.showSetting = !state.showSetting" type="primary" icon="Setting" />
					</el-tooltip>
				</div>
			</div>
			<div class="float-left main-title">
				<span class="design-title">低代码引擎-规则引擎</span>
			</div>
			<div class="float-right external-link">
				<div style="margin-right: 10px; display: flex">
					<el-tooltip effect="dark" content="切换主题颜色">
						<div @click="showColor = true" class="themeIcon">
							<SvgIcon name="zhuti" :size="18" />
						</div>
					</el-tooltip>
					<el-tooltip effect="dark" content="切换主题颜色">
						<div @click="changeDark" class="themeIcon">
							<SvgIcon :name="state.isDark ? 'moon' : 'sun'" :size="18" />
						</div>
					</el-tooltip>
				</div>
			</div>
		</el-header>
		<el-container>
			<transition name="h1">
				<el-aside v-show="state.showAside" class="side-panel">
					<widget-panel />
				</el-aside>
			</transition>
			<el-container class="center-layout-container">
				<el-header class="toolbar-header">
					<toolbar></toolbar>
				</el-header>
				<el-main class="form-widget-main" id="main">
					<div ref="container" id="container" class="container-box"
						style="height: calc(100% - 2px); width: calc(100% - 2px)"></div>
				</el-main>
			</el-container>
			<transition name="h2">
				<el-aside v-show="state.showSetting" class="setting-panel">
					<setting-panel></setting-panel>
				</el-aside>
			</transition>
		</el-container>
	</el-container>
	<el-dialog v-model="showColor" title="主题颜色选择" width="30%" draggable center>
		<color></color>
	</el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, provide, reactive, ref, watch } from 'vue';
import { useDark } from '@vueuse/core';
import { useToggle } from '@vueuse/shared';
import { Config, FlowDesign, FlowSelected } from './flow-design';
import { getFlowOptions, initFlow } from './init-container';
import '@logicflow/extension/lib/style/index.css';
import '@logicflow/core/dist/style/index.css';
import { rule_bases, rule_gateway, rule_server, rule_other } from './config';
import { getLightColor } from '../../../utils/theme';
import { NextLoading } from '../../../utils/loading';
import { GraphConfigData, NodeConfig } from '@logicflow/core';
import SvgIcon from '../../component/svgIcon/index.vue';

const emit = defineEmits(['onSave']);
const props = defineProps({
	code: Object,
});

const state = reactive<{
	flowDesign: FlowDesign; // 当前整个设计属性
	selected: FlowSelected; // 当前被选择的节点对应的组件
	currentTab: string; //当前左侧菜单类型
	showAside: boolean;
	showSetting: boolean;
	isDark: boolean;
}>({
	flowDesign: {
		globalColor: '#D49BEF',
		openRule: false,
		setting: {
			describe: '',
			grid: {
				size: 20,
				open: false,
				type: 'mesh',
			},
		},
	},
	selected: {
		name: '选择节点',
	},
	currentTab: 'rulechain',
	showAside: true,
	showSetting: true,
	isDark: false,
});

let dataCode: GraphConfigData = { nodes: [], edges: [] };
const initData = () => {
	if (window.nextLoading === undefined) NextLoading.start();
	console.log('props.code', props.code);

	if (props.code) {
		if (props.code.lfData) {
			dataCode = JSON.parse(JSON.stringify(props.code.lfData.dataCode));
		} else {
			dataCode = {
				nodes: [
					{
						id: '3698d32f-4711-47ac-88cb-ee7ef9db27cb',
						type: 'StartNode',
						x: 108,
						y: 378,
						properties: {
							status: false,
						},
						zIndex: 1002,
						text: {
							x: 118,
							y: 378,
							value: '开始',
						},
					},
				],
				edges: [],
			};
		}
		if (props.code.lfData) {
			state.flowDesign = props.code.lfData;
		}
	}
};

const isDark = useDark();
const toggleDark = useToggle(isDark);

const showColor = ref(false);
const container = ref<HTMLElement | undefined>();
const groups = ref<any>({});

watch(
	() => props.code,
	() => {
		initData();
		if (state.flowDesign.globalColor) {
			onColorPickerChange(state.flowDesign.globalColor);
		}
		if (!container.value) {
			console.log('error container is null');
			return;
		}
		const logicflowOptions = getFlowOptions(container.value, 'design');
		if (state.flowDesign.setting.grid.open) {
			logicflowOptions.grid = {
				visible: true,
				type: state.flowDesign.setting.grid.type,
				size: state.flowDesign.setting.grid.size,
				config: {
					color: '#eeeeee',
					thickness: 2,
				},
			};
		}
		modeler.initLogicFlow(logicflowOptions);

		if (dataCode) {
			modeler.lf?.renderRawData(dataCode);
		}
		if (window.nextLoading === true) NextLoading.done();
	},
	{ deep: true }
);
const onSave = (code: any) => {
	emit('onSave', code);
};

// 注册组件
const register = (type: string, name = '基础组件', icon: string, components: Array<Config> = [], order = 0) => {
	if (!groups.value[type]) {
		groups.value[type] = [];
	}
	const index = groups.value[type].findIndex((group: any) => group.name === name);
	if (!components.length) {
		return;
	}
	if (index > -1) {
		groups.value[type][index].components = components;
	} else {
		groups.value[type].push({ name, icon, components, order });
	}
};

const registerComponents = () => {
	register('rule', '基础组件', 'base', rule_bases, 1);
	register('rule', '网关节点', 'filter', rule_gateway, 2);
	register('rule', '服务节点', 'store', rule_server, 3);
	register('form', '其他', 'document', rule_other, 1);
};

registerComponents();

const modeler = initFlow();

// 获取全局变量
const getLfData = () => {
	let data = modeler.lf?.getGraphRawData();
	// console.log(' modeler', modeler.lf?.getSnapshotBase64('#fff'));

	let lfData = JSON.parse(JSON.stringify(state.flowDesign));
	return {
		lfData: lfData,
		data: data,
		ruleBase64: modeler.lf?.getSnapshotBase64('#fff'),
	};
};

// 暗黑模式
const changeDark = () => {
	state.isDark = !state.isDark;
	toggleDark();
};

// 修改全局样式
const onColorPickerChange = (color: any) => {
	state.flowDesign.globalColor = color;
	document.documentElement.style.setProperty('--el-color-primary', color);
	for (let i = 1; i <= 9; i++) {
		document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, getLightColor(color, i / 10));
	}
};

// provide context
provide('state', Object.assign(state, { onSave, getLfData, onColorPickerChange }));
provide('groups', groups);

// init
onMounted(() => {
	// initData();
	// if (state.flowDesign.globalColor) {
	// 	onColorPickerChange(state.flowDesign.globalColor);
	// }
	// if (!container.value) {
	// 	console.log('error container is null');
	// 	return;
	// }
	// const logicflowOptions = getFlowOptions(container.value, 'design');
	// if (state.flowDesign.setting.grid.open) {
	// 	logicflowOptions.grid = {
	// 		visible: true,
	// 		type: state.flowDesign.setting.grid.type,
	// 		size: state.flowDesign.setting.grid.size,
	// 		config: {
	// 			color: '#eeeeee',
	// 			thickness: 2,
	// 		},
	// 	};
	// }
	// modeler.initLogicFlow(logicflowOptions);
	// if (dataCode) {
	// 	modeler.lf?.renderRawData(dataCode);
	// }
	// if (window.nextLoading === true) NextLoading.done();
});
</script>

<style scoped lang="scss"></style>
